package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"yun_image/config/api"
	"yun_image/entity"
	"yun_image/service"
)

func getCategoriesByAccount(context *gin.Context) {
	var user entity.User
	userVal, _ := context.Get("user")
	user, _ = userVal.(entity.User)
	var categories []entity.Category
	err := service.GetCategoriesByAccount(&categories, user.Account)
	if err != nil {
		context.String(http.StatusInternalServerError, "")
		return
	}
	context.JSON(http.StatusOK, categories)
}
func saveCategory(context *gin.Context) {
	description := context.PostForm("description")
	categoryName := context.PostForm("categoryName")
	if description == "" || categoryName == "" {
		context.String(http.StatusInternalServerError, "")
		return
	}
	userVal, _ := context.Get("user")
	user, _ := userVal.(entity.User)
	category := entity.Category{
		Account:      user.Account,
		CategoryName: categoryName,
		Description:  description,
	}
	err := service.SaveCategory(&category)
	if err != nil {
		context.String(http.StatusInternalServerError, "")
		return
	}
	context.JSON(http.StatusOK, category)
}
func removeCategory(context *gin.Context) {
	userVal, _ := context.Get("user")
	user, _ := userVal.(entity.User)
	idStr := context.PostForm("id")
	id, err := strconv.Atoi(idStr)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
		return
	}
	err = service.RemoveCategory(id, user.Account)
	if err != nil {
		context.String(http.StatusInternalServerError, err.Error())
		return
	}
	context.JSON(http.StatusOK, gin.H{
		"success": true,
	})
}
func startCategoryApi() {
	router.POST(api.GetCategoriesByAccountPath, getCategoriesByAccount)
	router.POST(api.SaveCategoryPath, saveCategory)
	router.POST(api.RemoveCategoryPath, removeCategory)
}
